﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Hrm.Core;
using Hrm.EntityFramework;
using Hrm.Web.Framework;
using Hrm.Services;
using Newtonsoft.Json;

namespace Hrm.Web.Areas.Permissions.Controllers
{
    [RoleAuthorize]
    public class UsersController : Controller
    {
        IUserService _userService;
        IRoleService _roleService;

        public UsersController(IUserService userService, IRoleService roleService)
        {
            _userService = userService;
            _roleService = roleService;
        }

        public ActionResult Index()
        {
            return View();
        }

        public JsonResult PageUsers(PageRequest<UserDto> request)
        {
            var result = _userService.GetPageList(request);
            return Json(result);
        }

        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            User user = _userService.GetById(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(User user)
        {
            if (ModelState.IsValid)
            {
                user.Password = EncryptionTool.getMd5(user.Password);
                this._userService.Insert(user);
                return RedirectToAction("Index");
            }

            return View(user);
        }

        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            User user = this._userService.GetById(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(User user)
        {
            if (ModelState.IsValid)
            {
                var model = this._userService.GetById(user.Id);
                if (TryUpdateModel(model, "", new string[] { "Name", "Telephone" }))
                    this._userService.Update(model);
                return RedirectToAction("Index");
            }
            return View(user);
        }

        [HttpPost]
        public JsonResult Delete(int id)
        {
            ResponseModel result = new ResponseModel();
            if (id == 0)
            {
                result.SetFailed("删除失败，参数不能为空！");
                return Json(result);
            }
            User user = this._userService.GetById(id);
            if (user == null)
            {
                result.SetFailed("删除失败，查询没有改数据！");
                return Json(result);
            }
            this._userService.UpdateDisabled(user);
            return Json(result);
        }

        public ActionResult AllocateRoles(int id = 0)
        {
            var model = this._userService.GetById(id);
            var roleIds = model.Roles != null ? model.Roles.Select(p => p.Id) : new List<int>();
            ViewBag.RoleIds = JsonConvert.SerializeObject(roleIds);
            ViewBag.UserId = id;
            return View();
        }

        [HttpPost]
        public JsonResult AllocateRolesSubmit(AllocateRolesDto request)
        {
            var result = new ResponseModel();
            var model = this._userService.GetById(request.UserId);
            var SelectRoleIds = request.SelectRoleIds ?? new List<int>();
            var RolesIds = request.RoleIds ?? new List<int>();
            var deleteRoleIds = RolesIds.Where(p => !SelectRoleIds.Contains(p));
            var addRoleIds = SelectRoleIds.Where(p => !RolesIds.Contains(p));
            try
            {
                if(model.Roles==null)
                {
                    model.Roles = new List<Role>();
                }
                else
                {
                    var deleteRoles = model.Roles.Where(p => deleteRoleIds.Contains(p.Id)).ToList();
                    deleteRoles.ForEach(p => model.Roles.Remove(p));
                }
                var addRoles = this._roleService.GetList(p => addRoleIds.Contains(p.Id)).ToList();
                addRoles.ForEach(p => model.Roles.Add(p));
                this._userService.Update(model);
            }
            catch (Exception ex)
            {
                result.SetFailed("操作失败:" + ex.Message);
            }
            return Json(result);
        }
    }
}
